package my.study.common.util;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

public class PageUtil {
    /**
     * 构造分页对象
     *
     * @return
     */
    public static <T> Page<T> buildPage(PageParams<?> params) {
        Page<T> page = new Page<>(params.getPageNum() <= 0 ? 1 : params.getPageNum(), params.getPageSize() <= 0 ? 10 : params.getPageSize());
        String sort = params.getSort();
        if (StringUtils.isNotBlank(sort)) {
            //驼峰 转 下划线, 再进行SQL过滤
            sort = SqlFilter.getSafeValue(StrUtil.toUnderlineCase(sort));
        } else {
            sort = "id";
        }
        page.setOptimizeCountSql(false);
        page.addOrder("asc".equals(params.getOrder("desc")) ? OrderItem.asc(sort) : OrderItem.desc(sort));
        return page;
    }

    /**
     * 生成分页结果对象
     *
     * @param page
     * @return
     */
    public static <T> PageResult<T> toPageResult(IPage<T> page) {
        PageResult<T> result = new PageResult<>();
        result.setSize(page.getSize());
        result.setPage(page.getCurrent());
        result.setTotalCount(page.getTotal());
        result.setTotalPage(page.getPages());
        result.setList(page.getRecords());
        return result;
    }

    /**
     * 生成分页结果对象
     *
     * @param page
     * @return
     */
    public static <T, S> StatisticPageResult<T, S> toPageResult(IPage<T> page, S statistic) {
        StatisticPageResult<T, S> result = new StatisticPageResult<>();
        result.setSize(page.getSize());
        result.setPage(page.getCurrent());
        result.setTotalCount(page.getTotal());
        result.setTotalPage(page.getPages());
        result.setList(page.getRecords());
        result.setStatistic(statistic);
        return result;
    }
}
